package com.lcw.lostandfound.controller;

import com.lcw.lostandfound.pojo.User;
import com.lcw.lostandfound.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(){
        return "login";
    }
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:index";
    }
    @RequestMapping("/register")
    public String register(){
        return "register";
    }
    @RequestMapping("/doLogin")
    public String dologin(String username, String password, HttpSession session, Model model){
        //MD5加密
        String MD5Password = DigestUtils.md5DigestAsHex((password + username).getBytes());
        User user = userService.doLogin(username,MD5Password);
        if (user!=null){
            session.setAttribute("user",user);
            return "redirect:index";
        }
        model.addAttribute("errorMsg","用户名或密码错误");
        return "login";
    }
    @ResponseBody
    @RequestMapping("/checkUsername")
    public Boolean checkUsername(String username){
        if (userService.findByName(username)!=null){
            return true;
        }
      return false;
    }
    @ResponseBody
    @RequestMapping(value = "/doRegister",method = RequestMethod.POST)
    public String doRegister(@RequestBody User user){
        //密码加密
        String password = DigestUtils.md5DigestAsHex((user.getPassword()+user.getUsername()).getBytes());
        user.setPassword(password);
        System.out.println(user);
        userService.addUser(user);
        return "注册成功";
    }
    @ResponseBody
    @RequestMapping(value = "/checkTel",method = RequestMethod.POST)
    public Boolean checkTel(String tel){
        if (userService.checkTel(tel)!=null){
            return true;
        }
        return false;
    }
    @ResponseBody
    @RequestMapping(value = "/sendSMS",method = RequestMethod.POST)
    public String sendSMS(String tel){
        return userService.sendSMS(tel);
    }



}
